#include <regx52.h>
#include "oled.h"
#include "HX711.h"
#include "Delay.h"
#include "Timer0.h"

//max weight is 5 kg

unsigned long tare_weight=84211;
float unit_price = 0;
sbit key_down = P3^6;
sbit key_up = P3^7;




int Calculate_diff_weight(){
    unsigned long Data = ReadCount();
    //84211
    return (int) (Data/100-tare_weight)/3.8; //g
}





unsigned char key() {
    if(P3_4==0) {
        Delayms(20);
        while (P3_4==0);
        Delayms(20);
        return 1;
    }
    if(key_down==0) {
        Delayms(20);
        while (key_down==0);
        Delayms(20);
        return 2;
    }
    if(key_up==0) {
        Delayms(20);
        while (key_up==0);
        Delayms(20);
        return 3;
    }
    return 0;
}



void try_change_price(){
    switch (key()){
    case 1:
        tare_weight = ReadCount()/100;
        OLED_Clear();
        break;
    case 2:
        unit_price -= 0.1;
        if(unit_price<0) unit_price = 0;
        break;
    case 3:
        unit_price += 0.1;
        break;
    }
}


//定时器中断函数模板
void Timer_0_hander() interrupt 1 {
    static unsigned int count = 0;

    // 重载定时器初值
    TL0 = 0x66;
    TH0 = 0xFC;

    // 清除TF0标志位
    TF0 = 0;

    // 增加计数器
    if (++count == 50) {    // 10ms
        count = 0;
        try_change_price();
    }
}





void main(){
    unsigned long weight;
    Timer0_Init();
    OLED_Init();
    HX711_Init();
    //tare_weight = ReadCount()/100;
    while(1){
        weight = Calculate_diff_weight();
        OLED_ShowString(1,1,"weight:");
        OLED_ShowSignedNum(2,1,weight,4);
        OLED_ShowString(2,6," g");
        OLED_ShowString(3,1,"unit:");
        OLED_ShowNum(3,8,(int)unit_price,3);
        OLED_ShowString(3,11,".");
        OLED_ShowNum(3,12,(int)(unit_price*10)%10,1);
        if(weight>5000) OLED_ShowString(4,1,"error overload!");
        else {
            OLED_ShowString(4,13,"   ");
            OLED_ShowString(4,1,"price:");
            OLED_ShowSignedNum(4,8,unit_price*weight,4);
        }
        
    }
}
